from bs4 import BeautifulSoup

from utils.req import get_request
# import requests

base_url = "https://www.rockland.com"

headers = {
    "accept": "*/*",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "no-cache",
    "pragma": "no-cache",
    "priority": "u=1, i",
    "referer": "https://www.rockland.com/",
    "sec-ch-ua": '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
}


def search_product(search_string):

    url = "https://www.rockland.com/Typeahead/All"
    params = {"searchString": search_string}
    response = get_request(url=url, headers=headers, params=params)

    res = response.json()
    products = res.get("Products", {}).get("Items", [])
    if products:
        return base_url + products[0]["Url"]
    return None


def get_product_detail(url):
    response = get_request(url=url, headers=headers)
    soup = BeautifulSoup(response.text, "html.parser")
    return soup


def extract_product_detail(soup):
    desc = soup.find("div", class_="product-section-body")
    if desc:
        return str(desc)
    return None


def process_product_detail(procode):
    style_html = """
    <style>.row{ height: 100%;}    .bottom-border-line {        border-bottom: 1px solid #cdcdcd    }    .product-section-body {        border-radius: 5px;        border: solid 1px #cdcdcd;        padding: 20px;        padding-left: 30px;        padding-right: 30px    }    .product-specification-headline {        font-size: 24px;        font-weight: bold;        color: #3087bc;        margin-top: 3rem;        margin-bottom: 1rem    }    .product-specification-item {        display: flex;        flex-direction: row;        margin-top: 8px    }    .product-specification-item label {        flex: 0 0 180px;        font-weight: bold;        color: #3d4d65    }    .product-specification-item label.new {        flex: 0 0 250px    }    .product-specification-item span {        margin-bottom: .5rem    }    .product-specification-item span+a {        line-height: 1.37;        color: #3d4d65    }</style>
    """
    url = search_product(procode)
    if url:
        html = get_product_detail(url)
        detail = extract_product_detail(html)
        if detail:
            return style_html + detail
    return None

if __name__ == "__main__":
    res = process_product_detail("18-8816-31")
    with open("rocklan.html", "w", encoding="utf-8") as f:
        f.write(res)
    # print(res)
